package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Hierarchy;
import com.sl.au.entity.Option;
import com.sl.au.entity.Part;
import com.sl.au.service.HierarchyService;
import com.sl.au.service.IdentifyService;
import com.sl.au.service.OptionService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

/**
 * 组织管理
 * 
 * @author yangdi
 *
 */
@RestController
@RequestMapping(value = "/ui/hierarchy")
public class HierarchyController extends BaseController {

	@Autowired
	HierarchyService hierarchyService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	IdentifyService identifyService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView modelAndView = this.createLayoutView("hierarchy/hierarchyindex");
		List<Option> options = optionService.getRepository().findByGroup("组织层级");
		modelAndView.addObject("options", options);
		return modelAndView;
	}
	
	/**
	 * 显示组织结构
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAllNodes",method = RequestMethod.GET)
	public Map<String,Object> getAllNodes(HttpServletRequest request)
	{
		Map<String,Object> map = new HashMap<String,Object>();
		//List<BussinessLevel> node=null;
		List<Hierarchy> node = null;
		
		//node=bussinessLevelService.getAllNodes();
		node = hierarchyService.getAllNodes();
		List<Map<String,Object>> nodeMap=new ArrayList<Map<String,Object>>();
		
		nodeMap=hierarchyService.getNodeMap(node);
		
		map.put("code", 1);
		map.put("nodes", nodeMap);
	
		return map;
	}
	
	/**
	 * 获取节点信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getNode",method = RequestMethod.GET)
	public Map<String,Object> getNode(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String Id=request.getParameter("Id");
		Hierarchy node = hierarchyService.getRepository().findOne(Id);
		map.put("node", node);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.POST)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<Hierarchy> modules=null;
		int count = 0;
		
		modules = hierarchyService.getHierarchyByKey(start, length, key, null, null);
		count=hierarchyService.getHierarchyByKeyCount(key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getchildrenpage", method = RequestMethod.POST)
	public Map<String,Object> getChildrenPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String id=request.getParameter("id");
		List<Hierarchy> modules=null;
		int count = 0;
		
		modules = hierarchyService.getChildrenHierarchyByKey(start, length, id, key, null, null);
		count=hierarchyService.getChildrenHierarchyByKeyCount(id, key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 保存/修改信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public MsgHelper saveHierarchy(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = null;
		String id = (String) map.get("id");
		String groupName = (String) map.get("groupName");
		String groupIdentify = (String) map.get("groupIdentify");
		String groupTelphone = (String) map.get("groupTelphone");
		String groupLevelId = (String) map.get("groupLevel");
		String groupParent = (String) map.get("groupParent");
		if(!StringUtils.hasText(groupParent)) {
			groupParent = null;
		}
		
		String sgroupScore = (String) map.get("groupScore");
		String sgroupScoreWeight = (String) map.get("groupScoreWeight");
		
		boolean userShow = ExdeUtil.str2boolean(map.get("userShow"));
		boolean partShow = ExdeUtil.str2boolean( map.get("partShow"));
		boolean gridShow = ExdeUtil.str2boolean( map.get("gridShow"));
		boolean eventShow = ExdeUtil.str2boolean( map.get("eventShow"));
		
		float groupScore = ExdeUtil.str2float(sgroupScore);
		float groupScoreWeight = ExdeUtil.str2float(sgroupScoreWeight);
		
		Option groupLevel = optionService.getRepository().findOne(groupLevelId);
		
		Hierarchy hierarchy = null;
		Hierarchy SameHierarchy = null;
		
		if(!id.equals("")){
			hierarchy = hierarchyService.getRepository().findOne(id);
			SameHierarchy = hierarchyService.getRepository().findTopByGroupParentAndGroupIdentify(hierarchy.getGroupParent(), groupIdentify);
			if(hierarchy.getGroupParent() == null || SameHierarchy == null || SameHierarchy.getId().equals(id)) {
				hierarchy.setUpdateTime(new Date());
				hierarchy.setGroupName(groupName);
				hierarchy.setGroupIdentify(groupIdentify);
				hierarchy.setGroupTelphone(groupTelphone);
				hierarchy.setGroupScore(groupScore);
				hierarchy.setGroupScoreWeight(groupScoreWeight);
				hierarchy.setGroupLevel(groupLevel);
				
				hierarchy.setGroupParent(groupParent);;

				hierarchy.setUserShow(userShow);
				hierarchy.setPartShow(partShow);
				hierarchy.setGridShow(gridShow);
				hierarchy.setEventShow(eventShow);
				
				hierarchyService.getRepository().save(hierarchy);
				msgHelper = MsgHelper.success();
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同组织编码,不能进行修改!");
			}
			
		}else{
			hierarchy = new Hierarchy();
			hierarchy.setGroupName(groupName);
			hierarchy.setGroupIdentify(groupIdentify);
			hierarchy.setGroupTelphone(groupTelphone);
			hierarchy.setGroupScore(groupScore);
			hierarchy.setGroupScoreWeight(groupScoreWeight);
			hierarchy.setGroupLevel(groupLevel);
			
			hierarchy.setGroupParent(groupParent);;
			
			hierarchy.setUserShow(userShow);
			hierarchy.setPartShow(partShow);
			hierarchy.setGridShow(gridShow);
			hierarchy.setEventShow(eventShow);
			
			if(groupParent != null) {
				SameHierarchy = hierarchyService.getRepository().findTopByGroupParentAndGroupIdentify(groupParent, hierarchy.getGroupIdentify());
				if(SameHierarchy == null) {
					int groupOrder = hierarchyService.getRepository().getHierarchyOrder(groupParent);
					hierarchy.setGroupOrder(groupOrder);
					hierarchy.setGroupParent(groupParent);
					hierarchyService.getRepository().save(hierarchy);
					hierarchyService.setHierarchyOrder(groupParent);
					msgHelper = MsgHelper.success();
					msgHelper.setMsg("添加成功！");
				}else {
					msgHelper = MsgHelper.failed();
					msgHelper.setMsg("此层级存在相同组织编码,不能进行绑定!");
				}
				
			}
		}
		return msgHelper;
	};
	
	/**
	 * 保存组织层级及上传图标
	 * @param hierarchy
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "saveHierarchyWithFile", method = RequestMethod.POST)
	public MsgHelper saveHierarchyWithFile(Hierarchy hierarchy ,@RequestParam(value = "file", required = false) MultipartFile file) {
		MsgHelper msgHelper = null;
		if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
			// 注意路径的构建
			String url = getUploadIconFilePath(this.fileUploadPath, "icon/Hierarchy", file);
			hierarchy.setIconAddress(url);
		}
		
		String groupParent = hierarchy.getGroupParent();
		if(!StringUtils.hasText(groupParent)) {
			groupParent = null;
		}
		
		Hierarchy SameHierarchy = null;
		if(!hierarchy.getId().equals("")){
			Hierarchy oldHierarchy = hierarchyService.getRepository().findOne(hierarchy.getId());
			SameHierarchy = hierarchyService.getRepository().findTopByGroupParentAndGroupIdentify(hierarchy.getGroupParent(), hierarchy.getGroupIdentify());
			if(oldHierarchy.getGroupParent() == null || SameHierarchy == null || SameHierarchy.getId().equals(hierarchy.getId())) {
				oldHierarchy.setUpdateTime(new Date());
				oldHierarchy.setGroupName(hierarchy.getGroupName());
				oldHierarchy.setGroupIdentify(hierarchy.getGroupIdentify());
				oldHierarchy.setGroupTelphone(hierarchy.getGroupTelphone());
				oldHierarchy.setGroupScore(hierarchy.getGroupScore());
				oldHierarchy.setGroupScoreWeight(hierarchy.getGroupScoreWeight());
				oldHierarchy.setGroupLevel(hierarchy.getGroupLevel());
				
				oldHierarchy.setGroupParent(groupParent);;

				oldHierarchy.setUserShow(hierarchy.isUserShow());
				oldHierarchy.setPartShow(hierarchy.isPartShow());
				oldHierarchy.setGridShow(hierarchy.isGridShow());
				oldHierarchy.setEventShow(hierarchy.isEventShow());
				
				oldHierarchy.setIconAddress(hierarchy.getIconAddress());

				oldHierarchy.setMemo(hierarchy.getMemo());
				
				hierarchyService.getRepository().save(oldHierarchy);
				msgHelper = MsgHelper.success();
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同组织编码,不能进行修改!");
			}
			
		}else{
			if(groupParent != null) {
				SameHierarchy = hierarchyService.getRepository().findTopByGroupParentAndGroupIdentify(groupParent, hierarchy.getGroupIdentify());
				if(SameHierarchy == null) {
					Hierarchy newHierarchy = new Hierarchy();
					
					newHierarchy.setGroupName(hierarchy.getGroupName());
					newHierarchy.setGroupIdentify(hierarchy.getGroupIdentify());
					newHierarchy.setGroupTelphone(hierarchy.getGroupTelphone());
					newHierarchy.setGroupScore(hierarchy.getGroupScore());
					newHierarchy.setGroupScoreWeight(hierarchy.getGroupScoreWeight());
					newHierarchy.setGroupLevel(hierarchy.getGroupLevel());
					
					newHierarchy.setUserShow(hierarchy.isUserShow());
					newHierarchy.setPartShow(hierarchy.isPartShow());
					newHierarchy.setGridShow(hierarchy.isGridShow());
					newHierarchy.setEventShow(hierarchy.isEventShow());
					
					newHierarchy.setIconAddress(hierarchy.getIconAddress());

					newHierarchy.setMemo(hierarchy.getMemo());
					
					int groupOrder = hierarchyService.getRepository().getHierarchyOrder(groupParent);
					newHierarchy.setGroupOrder(groupOrder);
					newHierarchy.setGroupParent(groupParent);
					hierarchyService.getRepository().save(newHierarchy);
					hierarchyService.setHierarchyOrder(groupParent);
					msgHelper = MsgHelper.success();
					msgHelper.setMsg("添加成功！");
				}else {
					msgHelper = MsgHelper.failed();
					msgHelper.setMsg("此层级存在相同组织编码,不能进行绑定!");
				}
			}else {
				Hierarchy newHierarchy = new Hierarchy();
				
				newHierarchy.setGroupName(hierarchy.getGroupName());
				newHierarchy.setGroupIdentify(hierarchy.getGroupIdentify());
				newHierarchy.setGroupTelphone(hierarchy.getGroupTelphone());
				newHierarchy.setGroupScore(hierarchy.getGroupScore());
				newHierarchy.setGroupScoreWeight(hierarchy.getGroupScoreWeight());
				newHierarchy.setGroupLevel(hierarchy.getGroupLevel());
				
				newHierarchy.setUserShow(hierarchy.isUserShow());
				newHierarchy.setPartShow(hierarchy.isPartShow());
				newHierarchy.setGridShow(hierarchy.isGridShow());
				newHierarchy.setEventShow(hierarchy.isEventShow());
				
				newHierarchy.setIconAddress(hierarchy.getIconAddress());
				
				newHierarchy.setMemo(hierarchy.getMemo());
				
				hierarchyService.setHierarchyOrder(groupParent);
				hierarchyService.getRepository().save(newHierarchy);
				msgHelper = MsgHelper.success();
				msgHelper.setMsg("添加成功！");
			}
		}
		return msgHelper;
	}
	
	/**
	 * 删除信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	public MsgHelper deleteHierarchy(@PathVariable("id") String id) {
		MsgHelper msgHelper = MsgHelper.success();
		hierarchyService.getRepository().delete(id);
		return msgHelper;
	}
	
	/**
	 * 绑定层级关系
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/saveNode",method = RequestMethod.POST)
	public Map<String,Object> saveNode(@RequestBody Map<String,Object> map){
		Map<String,Object> msg = new HashMap<String,Object>();
		String id = (String) map.get("id");
		String parentId = String.valueOf(map.get("parentId"));
		Hierarchy hierarchy = hierarchyService.getRepository().findOne(id);
		Hierarchy SameHierarchy = hierarchyService.getRepository().findTopByGroupParentAndGroupIdentify(parentId, hierarchy.getGroupIdentify());
		if(SameHierarchy == null) {
			int groupOrder = hierarchyService.getRepository().getHierarchyOrder(parentId);
			hierarchy.setGroupOrder(groupOrder);
			hierarchy.setGroupParent(parentId);
			hierarchyService.getRepository().save(hierarchy);
			msg.put("code", 1);
			msg.put("Hierarchy", hierarchy);
		}else {
			msg.put("code", -1);
			msg.put("msg", "此层级存在相同组织编码,不能进行绑定!");
		}
		return msg;
	};
	
	/**
	 * 移除节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/deleteNodes")
	public Map deleteNode(@RequestBody Map<String,Object> map)
	{
		String str=String.valueOf(map.get("str"));
		//暂未使用
		//String selectPId= String.valueOf(map.get("selectPId"));
		String ids[]=str.split(",");
		//删除用户信息，暂未处理
		//businesssellerBaseInfoService.deleteBussinessLevel(ids);
		hierarchyService.deleteNodes(ids);
		map.put("code", 1);
		return map;
	}
	
	/**
	 * 移动节点节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/move")
	public Map moveNode(@RequestBody Map<String,Object> map)
	{
		String id=String.valueOf(map.get("id"));
		String targetId = String.valueOf(map.get("targetId"));
		String moveType = String.valueOf(map.get("moveType"));
		Hierarchy targetNode = hierarchyService.getRepository().findOne(targetId);
		Hierarchy node = hierarchyService.getRepository().findOne(id);
		String nodeGroupParent = node.getGroupParent();
		String groupParent = null;
		Hierarchy SameHierarchy = null;
		int groupOrder = 0;
		if("inner".equals(moveType)) {
			groupParent = targetNode.getId();
			SameHierarchy = hierarchyService.getRepository().findTopByGroupParentAndGroupIdentify(groupParent, node.getGroupIdentify());//判断是否存在相同的组织编码
			if(SameHierarchy == null) {
				node.setGroupParent(groupParent);
				node.setGroupOrder(groupOrder);
				hierarchyService.getRepository().save(node);
				//更新组织下面的编码信息
				identifyService.updateHierarchyIdentify(id);
			}
		}else {
			groupParent = targetNode.getGroupParent();
			String oldGroupParent = node.getGroupParent();
			SameHierarchy = hierarchyService.getRepository().findTopByGroupParentAndGroupIdentify(groupParent, node.getGroupIdentify());
			if(SameHierarchy == null || SameHierarchy.getId().equals(node.getId())) {
				groupOrder = targetNode.getGroupOrder();
				if("next".equals(moveType)) {
					groupOrder = groupOrder + 1;
				}else {
					groupOrder = groupOrder - 1;
				}
				node.setGroupParent(groupParent);
				node.setGroupOrder(groupOrder);
				hierarchyService.getRepository().save(node);
				if(!groupParent.equals(oldGroupParent)) {
					//更新组织下面的编码信息
					identifyService.updateHierarchyIdentify(id);
				}
			}
		}
		if(SameHierarchy == null || SameHierarchy.getId().equals(node.getId())) {
			//拉动之后进行重新排序
			hierarchyService.setHierarchyOrder(groupParent);
			//原始数据进行排序
			hierarchyService.setHierarchyOrder(nodeGroupParent);
			map.put("code", 1);
		}else {
			map.put("code", -1);
			map.put("msg", "此层级存在相同组织编码,不能进行绑定!");
		}
		return map;
	}
}
